<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

/**
 * 翻译任务队列模型
 */
class TranslationJob extends Model
{
    protected $table = 'translation_jobs';

    protected function getOptions(): array
    {
        return [
            'type'               => [
                'target_languages' => 'json',
            ],
            'autoWriteTimestamp' => true,
            'jsonAssoc'          => true,
        ];
    }

    // 任务状态常量
    const STATUS_PENDING = 0;      // 待处理
    const STATUS_PROCESSING = 1;   // 处理中
    const STATUS_COMPLETED = 2;    // 已完成
    const STATUS_FAILED = 3;       // 失败

    /**
     * 获取待处理的任务
     */
    public static function getPendingJobs($limit = 10)
    {
        return self::where('status', self::STATUS_PENDING)
            ->where('attempts', '<', 3)
            ->order('priority', 'desc')
            ->order('created_at', 'asc')
            ->limit($limit)
            ->select();
    }

    /**
     * 创建翻译任务
     */
    public static function createJob($tableName, $recordId, $fieldName, $targetLanguages, $priority = 0)
    {
        return self::updateOrCreate([
            'table_name' => $tableName,
            'record_id'  => $recordId,
            'field_name' => $fieldName,
        ], [
            'target_languages' => $targetLanguages,
            'priority'         => $priority,
            'status'           => self::STATUS_PENDING,
            'attempts'         => 0,
            'error_message'    => null
        ]);
    }

    /**
     * 标记任务为处理中
     */
    public function markAsProcessing()
    {
        return $this->save([
            'status'   => self::STATUS_PROCESSING,
            'attempts' => $this->attempts + 1
        ]);
    }

    /**
     * 标记任务为完成
     */
    public function markAsCompleted()
    {
        return $this->save([
            'status'        => self::STATUS_COMPLETED,
            'error_message' => null
        ]);
    }

    /**
     * 标记任务为失败
     */
    public function markAsFailed($errorMessage)
    {
        return $this->save([
            'status'        => self::STATUS_FAILED,
            'error_message' => $errorMessage
        ]);
    }

    /**
     * 重置任务状态
     */
    public function resetJob()
    {
        return $this->save([
            'status'        => self::STATUS_PENDING,
            'attempts'      => 0,
            'error_message' => null
        ]);
    }

    /**
     * 获取任务统计
     */
    public static function getJobStats()
    {
        $stats = [
            'total'      => self::count(),
            'pending'    => self::where('status', self::STATUS_PENDING)->count(),
            'processing' => self::where('status', self::STATUS_PROCESSING)->count(),
            'completed'  => self::where('status', self::STATUS_COMPLETED)->count(),
            'failed'     => self::where('status', self::STATUS_FAILED)->count(),
        ];

        $stats['success_rate'] = $stats['total'] > 0
            ? round($stats['completed'] / $stats['total'] * 100, 2)
            : 0;

        return $stats;
    }

    /**
     * 清理旧的已完成任务
     */
    public static function cleanCompletedJobs($days = 30)
    {
        return self::where('status', self::STATUS_COMPLETED)
            ->where('created_at', '<', date('Y-m-d H:i:s', strtotime("-{$days} days")))
            ->delete();
    }

    /**
     * 重试失败的任务
     */
    public static function retryFailedJobs($maxAttempts = 3)
    {
        return self::where('status', self::STATUS_FAILED)
            ->where('attempts', '<', $maxAttempts)
            ->update([
                'status'        => self::STATUS_PENDING,
                'error_message' => null
            ]);
    }

    /**
     * 获取状态文本
     */
    public function getStatusTextAttr()
    {
        $statusMap = [
            self::STATUS_PENDING    => '待处理',
            self::STATUS_PROCESSING => '处理中',
            self::STATUS_COMPLETED  => '已完成',
            self::STATUS_FAILED     => '失败',
        ];

        return $statusMap[$this->status] ?? '未知';
    }
}
